package org.dstart.object.color
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	
	import org.dstart.object.color.sub.*;

	public class ColorObject extends Sprite
	{
		public static const CLICK_COLOR:String	= "clickColor";		//	鼠标选择颜色
		
		private var m_bgSprite:Sprite;				//	取色器背景框
		private var m_objColor:ColorListObject;		//	色块板
		private var m_nowSprite:Sprite;				//	当前颜色
		private var m_txtColor:TextField;			//	颜色文字内容

		public function ColorObject(xx:Number = 0, yy:Number = 0, isShowText:Boolean = false)
		{
			InitObject(xx, yy, isShowText);
			InitListener();
		}		
		
		/** 读取当前颜色值 */
		public function get color():uint
		{
			return m_objColor.now;
		}
		
		/** 绘制颜色 **/
		public function set color(col:uint):void
		{
			this.m_objColor.now = col;
			
			DrawRectangle(m_nowSprite, col);
		}		

		//------------------------------------------------
		
		private function InitObject(xx:Number, yy:Number, isShowText:Boolean):void
		{
			m_bgSprite = new Sprite();
						
			m_nowSprite = new Sprite();
			m_nowSprite.x = 5;
			m_nowSprite.y = 4;
			
			m_objColor = new ColorListObject(5, 25);
			
			m_txtColor = new TextField();
			m_txtColor.x = 55;
			m_txtColor.y = 5;
			m_txtColor.width = 100;	
			m_txtColor.height = 16;
			m_txtColor.selectable = false;		
			m_txtColor.visible = isShowText;
			
			addChild(m_bgSprite);
			addChild(m_nowSprite);
			addChild(m_objColor);
			addChild(m_txtColor);

			this.x = xx;
			this.y = yy;
			
			DrawRectangle(m_bgSprite, 0xFFFFFF, m_objColor.width + 10, m_objColor.height + 30);
			DrawRectangle(m_nowSprite, m_objColor.now);
		}
		
		private function InitListener():void
		{
			m_objColor.addEventListener(MouseEvent.CLICK, onColorClick);
			
			m_objColor.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMoveEvent);
			m_objColor.addEventListener(MouseEvent.ROLL_OUT, onMouseMoveEvent);
		}

		/** 为指定 Sprite 对象绘制填充，后面的默认值是为 取色器 对象准备的 **/
		private function DrawRectangle(spr:Sprite, col:uint, ww:Number = 40, hh:Number = 15):void
		{
			spr.graphics.clear();
			spr.graphics.lineStyle(0, 0x000000, 1);
			spr.graphics.beginFill(col, 1);
			spr.graphics.drawRect(0, 0, ww, hh);
			spr.graphics.endFill();
		}
		
		/** 鼠标滑动时触发修改颜色事件 **/
		private function onMouseMoveEvent(e:MouseEvent):void
		{
			DrawRectangle(m_nowSprite, m_objColor.color);
			
			if(m_txtColor.visible)
			{
				m_txtColor.text = String("000000" + m_objColor.color).substr(-6);
				m_txtColor.textColor = m_objColor.color;
			}
		}
		
		/** 鼠标点击颜色时触发事件 **/
		private function onColorClick(e:MouseEvent):void
		{			
			DrawRectangle(m_nowSprite, m_objColor.color);

			m_objColor.now = m_objColor.color;
			
			this.dispatchEvent(new Event(ColorObject.CLICK_COLOR));
		}
	}
}